package com.gbr.screenrecorder;

import java.awt.Rectangle;

import com.gbr.application.action.RecordAction;
import com.gbr.application.model.Capture;
import com.ng.framework.AbstractPlugin;
import com.ng.framework.model.IModelController;
import com.ng.framework.service.action.IActionListener;
import com.ng.framework.service.action.IActionService;
import com.ng.framework.service.log.ILogService;
import com.ng.framework.service.log.LogLevel;

public class RecordingPlugin extends AbstractPlugin {
    private ILogService             logService;
    private ScreenRecorder          recorder;
    private IModelController        modelController;
    private IActionService          actionService;

    private RecordingActionListener recordingActionListener = new RecordingActionListener();

    @Override
    protected void activateComponent() {
        logService.log(getClass(), LogLevel.TRACE, "Activating");
        actionService.addListener(RecordAction.class, recordingActionListener);
    }

    @Override
    protected void deactivateComponent() {
        logService.log(getClass(), LogLevel.TRACE, "Dectivating");
        actionService.removeListener(RecordAction.class, recordingActionListener);
    }

    public final void bindService(IModelController service) {
        modelController = service;
    }

    public final void unbindService(IModelController service) {
        modelController = null;
    }

    public final void bindService(IActionService service) {
        actionService = service;
    }

    public final void unbindService(IActionService service) {
        actionService = null;
    }

    public final void bindService(ILogService service) {
        logService = service;
    }

    public final void unbindService(ILogService service) {
        logService = null;
    }
    
    private void record(Rectangle r, String name) {
        recorder = new ScreenRecorder(r, name);
        recorder.startRecording();
    }

    class RecordingActionListener implements IActionListener<RecordAction> {
        @Override
        public void actionPerformed(final RecordAction action) {
            if (action.isRecord()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        record(action.getRect(), action.getName());
                    }
                }).start();
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        recorder.stopRecording();
                        Capture capture = recorder.getCapture();
                        modelController.merge(capture);
                    }
                }).start();
            }
        }
    }
}
